#用户信息管理的视图文件
import random
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime, timezone

from myadmin.models import Users

def index(request,pIndex=1):
    umod = Users.objects
    # 过滤掉 status 为 9 的用户
    #ulist = umod.exclude(status=9)   #方法1
    ulist = umod.filter(~Q(status=9)) #方法2
    mywhere=[]

    # 获取排序参数
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', 'asc')

    # 根据排序参数对用户列表进行排序
    if sort:
        if order == 'desc':
            sort = f'-{sort}'
        try:
            ulist = ulist.order_by(sort)
            mywhere.extend([f'sort={sort.replace("-", "")}', f'order={order}'])
        except:
            # 处理无效排序字段的情况
            pass

    #获取并判断搜索条件
    kw = request.GET.get("keyword",None)
    if kw:
        ulist = ulist.filter(Q(username__contains=kw) | Q(email__contains=kw))
        mywhere.append('keyword='+kw)

    #获取、判断并封装状态status搜索条件
    status = request.GET.get('status','')
    if status != '':
        ulist = ulist.filter(status=status)
        mywhere.append("status"+status)

    #执行分页处理
    pIndex = int(pIndex)
    page = Paginator(ulist,5) #以每页5条数据分页
    maxpages = page.num_pages #获取最大页数
    #判断当前页是否越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex) #获取当前页数
    plist = page.page_range #获取页码列表信息
    context = {"userslist":list2,'plist':plist,'pIndex':pIndex,'maxpages':maxpages,'mywhere':mywhere}
    return render(request,"myadmin/users/index.html",context)

def add(request):
    '''加载信息添加表单'''
    return render(request,"myadmin/users/add.html")


def insert(request):
    '''执行信息添加'''
    try:
        ob = Users()
        ob.user_id = request.POST.get('user_id')
        ob.username = request.POST.get('username')
        ob.password = request.POST.get('password')
        ob.status = 1
        ob.phone = request.POST.get('phone')
        ob.email = request.POST.get('email')
        ob.full_name = request.POST.get('full_name')
        ob.gender = request.POST.get('gender')
        ob.birth_date = request.POST.get('birth_date')
        ob.height_cm = request.POST.get('height_cm')
        ob.weight_kg = request.POST.get('weight_kg')
        ob.created_at = datetime.now()
        ob.updated_at = datetime.now()
        ob.has_autoimmune_disease = request.POST.get('has_autoimmune_disease')
        ob.autoimmune_disease_type = request.POST.get('autoimmune_disease_type')
        ob.has_diabetes = request.POST.get('has_diabetes')
        ob.diabetes_type = request.POST.get('diabetes_type')
        ob.other_chronic_conditions = request.POST.get('other_chronic_conditions')
        ob.save()
        context = {'info':"添加成功！"}
    except Exception as err:
        print(err)
        context = {'info':"添加失败！"}
    return render(request,"myadmin/info.html",context)

def delete(request,uid=0):
    '''执行信息删除'''
    try:
        ob = Users.objects.get(user_id=uid)
        ob.status = 9
        ob.updated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        #ob.delete()  # 真正删除用户信息
        context = {'info':"删除成功！"}
    except Users.DoesNotExist:
        # 处理用户不存在的情况
        context = {'info':"删除失败：用户不存在！"}
    except Exception as err:
        # 处理其他异常
        print(f"删除用户时出错: {err}")
        context = {'info':"删除失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)

def edit(request,uid=0):
    '''加载信息编辑表单'''
    try:
        ob = Users.objects.get(user_id=uid)
        #ob.status = request.POST.get('status')
        context = {'users':ob}
        return render(request, "myadmin/users/edit.html", context)
    except Exception as err:
        print(err)
        context = {'info':"没有找到要修改的信息！"}
    return render(request, "myadmin/info.html", context)

def update(request,uid):
    '''执行信息编辑'''
    try:
        ob = Users.objects.get(user_id=uid)
        ob.username = request.POST['username'] #上传修改后的信息，必传
        birth_date_str = request.POST.get('birth_date')
        ob.birth_date = birth_date_str if birth_date_str else None  # 为空时存None
        ob.full_name = request.POST['full_name'] #必传
        ob.email = request.POST['email'] #必传
        ob.phone = request.POST['phone'] #必传
        ob.gender = request.POST.get('gender')
        ob.height_cm = request.POST.get('height_cm') if request.POST.get('height_cm') else None
        ob.weight_kg = request.POST.get('weight_kg') if request.POST.get('weight_kg') else None
        ob.has_autoimmune_disease = request.POST.get('has_autoimmune_disease')
        ob.autoimmune_disease_type = request.POST.get('autoimmune_disease_type')
        ob.has_diabetes = request.POST.get('has_diabetes')
        ob.diabetes_type = request.POST.get('diabetes_type')
        ob.has_hypertension = request.POST.get('has_hypertension')
        ob.has_hyperlipidemia = request.POST.get('has_hyperlipidemia')
        ob.other_chronic_conditions = request.POST.get('other_chronic_conditions')
        ob.updated_at = datetime.now()
        ob.status = request.POST.get('status')
        ob.save()
        context = {'info':"修改成功"}
    except Exception as err:
        print(err)
        context = {'info':"修改失败！"}
    return render(request, "myadmin/info.html", context)

@property
def diet_records_count(self):
        """总记录次数：实时统计关联的饮食记录数量"""
        return self.diet_records.count()  # 利用ORM的count()实现实时查询
    
@property
def achieved_goals_count(self):
        """目标达成次数：根据最新记录实时计算"""
        achieved_count = 0
        # 获取用户当天的饮食计划（假设按天设定目标）
        today = timezone.now().date()
        daily_plan = self.diet_plans.filter(
            start_date__lte=today,
            end_date__gte=today,
            is_active=True
        ).first()
        
        if daily_plan:
            # 计算当天已摄入总热量
            today_records = self.diet_records.filter(
                record_time__date=today
            )
            total_calories = sum(record.calories for record in today_records)
            
            # 判断是否达成目标（例如：达到目标热量的90%以上）
            if total_calories >= daily_plan.target_calories * 0.9:
                achieved_count += 1
                
            # 如果需要累计历史达成次数，可扩展查询历史记录
            # 例如：查询过去30天的达成情况
            # past_records = self.diet_records.filter(...)
            # ...
        return achieved_count


def get_goal_achievement_rate(self):
        """计算目标达成率（百分比）"""
        if self.diet_records_count == 0:
            return 0
        return round((self.achieved_goals_count / self.diet_records_count) * 100)
